# Header:4bytes BinMsgLen + 4bytes MsgId Content: BinMsgLen: BinMsg)
# 利用struct模块

import struct


def pack(msg_id, content):
    bin_msg = content_to_bin_msg(content)
    bin_msg_size = len(bin_msg)

    header = struct.pack("!2I", bin_msg_size, msg_id)
    send_data = header + bin_msg
    return send_data

def content_to_bin_msg(content):
    content_str = f'{content}'
    return content_str.encode('utf-8')

def bin_msg_to_content(bin_msg):
    msg:str = bin_msg.decode('utf-8')
    kvs_content = eval(msg)
    content = bin_msg_to_content2(kvs_content)
    return content

def bin_msg_to_content2(kvs_content):
    content = {}
    for key, value in kvs_content:
        if type(value) == list and len(value) > 0:
            if type(value[0]) == list:
                value = bin_msg_to_content3(value)        
        content[key] = value
    return content

def bin_msg_to_content3(value):
    tmp_value = []
    for each in value:
        value = bin_msg_to_content2(each)
        tmp_value.append(value)
    return tmp_value
